package com.uzai.console.service.user.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.enums.GroupSendStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.user.app.*;
import com.uzai.console.dto.user.wechatuser.TimeVO;
import com.uzai.console.dto.user.wechatuser.UpdateDefaultClient;
import com.uzai.console.dto.user.wechatuser.WechatUserUpdateDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.entity.*;
import com.uzai.console.enums.SmsType;
import com.uzai.console.mapper.*;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.user.AppUserService;
import com.uzai.console.service.user.AppUserSyncService;
import com.uzai.console.service.user.MarketingRewardsBlackListService;
import com.uzai.console.vo.user.app.AppUserMinMaxCreateTimeVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/***
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class AppUserSyncServiceImpl implements AppUserSyncService {

    Logger logger = LoggerFactory.getLogger(AppUserSyncServiceImpl.class);

    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private JdOrderMapper jdOrderMapper;
    @Autowired
    private PddOrderMapper pddOrderMapper;
    @Autowired
    private VphOrderMapper vphOrderMapper;
    @Autowired
    private MtOrderMapper mtOrderMapper;
    @Autowired
    private DyOrderMapper dyOrderMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private MarketingRewardsBlackListService marketingRewardsBlackListService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;

    /**
     * 查询结果添加群发任务
     *
     * @param batchSendMsgDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    @Override
    public void sendMessageToUserSelectedSync(AppUserBatchSendMsgDto batchSendMsgDto) {
        //记录发送总数
        int totalCount_parent_succ = 0;
        AppUserQuery wechatUserQuery = batchSendMsgDto.getWechatUserQuery();
        wechatUserQuery.setMerId(batchSendMsgDto.getMerId());
        //查询条件中是否包含机器人id,
        if (wechatUserQuery.getDeviceUniqueId() != null) {//条件中带机器人id,则添加到机器人列表中
            int totalCount_son_succ = appUserService.groupSendMsgByDeviceUniqueId(batchSendMsgDto);
            totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
        } else if (wechatUserQuery.getDeviceUniqueIdList() != null && wechatUserQuery.getDeviceUniqueIdList().size() > 0) {
            List<Long> deviceUniqueIdList = wechatUserQuery.getDeviceUniqueIdList();
            for (Long devieUniqueId : deviceUniqueIdList) {
                try {
                    AppUserBatchSendMsgDto wechatUserBatchSendMsgDto_deviceUniqueId = new AppUserBatchSendMsgDto();
                    wechatUserBatchSendMsgDto_deviceUniqueId.setMerId(batchSendMsgDto.getMerId());
                    wechatUserBatchSendMsgDto_deviceUniqueId.setWechatUserGroupSendMsgDto(batchSendMsgDto.getWechatUserGroupSendMsgDto());
                    wechatUserBatchSendMsgDto_deviceUniqueId.setGroupSendJobParentId(batchSendMsgDto.getGroupSendJobParentId());
                    AppUserQuery wechatUserQuery_deviceUniqueId = new AppUserQuery();
                    BeanUtils.copyProperties(wechatUserQuery, wechatUserQuery_deviceUniqueId);
                    wechatUserQuery_deviceUniqueId.setDeviceUniqueId(devieUniqueId);
                    wechatUserQuery_deviceUniqueId.setDeviceUniqueIdList(null);
                    wechatUserBatchSendMsgDto_deviceUniqueId.setWechatUserQuery(wechatUserQuery_deviceUniqueId);
                    int totalCount_son_succ = appUserService.groupSendMsgByDeviceUniqueId(wechatUserBatchSendMsgDto_deviceUniqueId);
                    totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
                } catch (Exception e) {
                    logger.error("-------sendMessageToUserSelectedSync is error; deviceUniqueId={}, error={}", wechatUserQuery.getDeviceUniqueId(), e.getMessage());
                }
            }
        } else {//如果没有，则查询该运营商所有的机器人
            DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
            deviceWechatInfoQuery.setMerId(batchSendMsgDto.getMerId());
            List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
            if (deviceWechatInfoList != null && deviceWechatInfoList.size() > 0) {
                for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList) {
                    try {
                        AppUserBatchSendMsgDto wechatUserBatchSendMsgDto_deviceUniqueId = new AppUserBatchSendMsgDto();
                        wechatUserBatchSendMsgDto_deviceUniqueId.setMerId(batchSendMsgDto.getMerId());
                        wechatUserBatchSendMsgDto_deviceUniqueId.setWechatUserGroupSendMsgDto(batchSendMsgDto.getWechatUserGroupSendMsgDto());
                        wechatUserBatchSendMsgDto_deviceUniqueId.setGroupSendJobParentId(batchSendMsgDto.getGroupSendJobParentId());
                        AppUserQuery wechatUserQuery_deviceUniqueId = new AppUserQuery();
                        BeanUtils.copyProperties(wechatUserQuery, wechatUserQuery_deviceUniqueId);
                        wechatUserQuery_deviceUniqueId.setMerId(batchSendMsgDto.getMerId());
                        wechatUserQuery_deviceUniqueId.setDeviceUniqueId(deviceWechatInfo.getId());
                        wechatUserQuery_deviceUniqueId.setDeviceUniqueIdList(null);
                        wechatUserBatchSendMsgDto_deviceUniqueId.setWechatUserQuery(wechatUserQuery_deviceUniqueId);
                        int totalCount_son_succ = appUserService.groupSendMsgByDeviceUniqueId(wechatUserBatchSendMsgDto_deviceUniqueId);
                        totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
                    } catch (Exception e) {
                        logger.error("-------sendMessageToUserSelectedSync is error; deviceUniqueId={}, error={}", wechatUserQuery.getDeviceUniqueId(), e.getMessage());
                    }
                }
            }
        }

        //全部执行完成之后，修改主任务状态
        if(batchSendMsgDto.getGroupSendJobParentId() != null){
            GroupSendJob groupSendJob = groupSendJobMapper.selectById(batchSendMsgDto.getGroupSendJobParentId(), batchSendMsgDto.getMerId());
            if(groupSendJob != null){
                groupSendJob.setStatus(GroupSendStatusEnum.NOT_START.getValue()); //将状态设置为未开始状态
                groupSendJob.setTotalCount(totalCount_parent_succ);
                groupSendJobMapper.updateTotalCountById(groupSendJob);

                //批量修改子任务的状态
                groupSendJobMapper.updateStatusByParentId(GroupSendStatusEnum.NOT_START.getValue(), batchSendMsgDto.getGroupSendJobParentId(), batchSendMsgDto.getMerId());
            }
        }

    }

    /**
     * 多选框选择会员添加群发任务
     *
     * @param msgBatchDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    @Override
    public void sendMessageToUserBatchSync(AppUserSendMsgBatchDto msgBatchDto) {
        //记录发送总数
        int totalCount_parent_succ = 0;
        //查询该运营商所有得机器人
        DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
        deviceWechatInfoQuery.setMerId(msgBatchDto.getMerId());
        List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
        if (deviceWechatInfoList != null && deviceWechatInfoList.size() > 0) {
            for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList) {
                try {
                    AppUserSendMsgBatchDto wechatUserSendMsgBatchDto_deviceUniqueId = new AppUserSendMsgBatchDto();
                    wechatUserSendMsgBatchDto_deviceUniqueId.setMerId(msgBatchDto.getMerId());
                    wechatUserSendMsgBatchDto_deviceUniqueId.setWechatUserGroupSendMsgDto(msgBatchDto.getWechatUserGroupSendMsgDto());
                    wechatUserSendMsgBatchDto_deviceUniqueId.setGroupSendJobParentId(msgBatchDto.getGroupSendJobParentId());
                    wechatUserSendMsgBatchDto_deviceUniqueId.setDeviceUniqueId(deviceWechatInfo.getId());
                    wechatUserSendMsgBatchDto_deviceUniqueId.setIdList(msgBatchDto.getIdList());
                    int totalCount_son_succ = appUserService.groupSendMsgByDeviceUniqueIdBatch(wechatUserSendMsgBatchDto_deviceUniqueId);
                    totalCount_parent_succ = totalCount_parent_succ + totalCount_son_succ;
                } catch (Exception e) {
                    logger.error("-------sendMessageToUserBatchSync is error; deviceUniqueId={}, error={}", deviceWechatInfo.getId(), e.getMessage());
                }
            }
        }

        //全部执行完成之后，修改主任务状态
        if(msgBatchDto.getGroupSendJobParentId() != null){
            GroupSendJob groupSendJob = groupSendJobMapper.selectById(msgBatchDto.getGroupSendJobParentId(), msgBatchDto.getMerId());
            if(groupSendJob != null){
                groupSendJob.setStatus(GroupSendStatusEnum.NOT_START.getValue()); //将状态设置为未开始状态
                groupSendJob.setTotalCount(totalCount_parent_succ);
                groupSendJobMapper.updateTotalCountById(groupSendJob);

                //批量修改子任务的状态
                groupSendJobMapper.updateStatusByParentId(GroupSendStatusEnum.NOT_START.getValue(), msgBatchDto.getGroupSendJobParentId(), msgBatchDto.getMerId());
            }
        }
    }

    /**
     * 查询结果定投筛选
     *
     * @param wechatUserBatchOptCpcDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    @Override
    public void optCpcToUserSelected(AppUserBatchOptCpcDto wechatUserBatchOptCpcDto) {
        if (wechatUserBatchOptCpcDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        AppUserOptCpcDto wechatUserOptCpcDto = wechatUserBatchOptCpcDto.getWechatUserOptCpcDto();
        if (wechatUserOptCpcDto == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if (wechatUserOptCpcDto.getCpaId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择定投项目");
        }

        Page<WechatUser> page = new Page<>();
        page.setSize(10);
        page.setCurrent(1);
//        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserBatchOptCpcDto.getWechatUserQuery());
//        while (wechatUserList != null && wechatUserList.size() > 0){
//            for (AppUser wechatUser : wechatUserList){
//                wechatUserOptCpcDto.setId(wechatUser.getId());
//                wechatUserService.optCpcToOneUser(wechatUserOptCpcDto);
//            }
//            //每次查询第一页
//            wechatUserList = wechatUserMapper.findByList(page, wechatUserBatchOptCpcDto.getWechatUserQuery());
//        }
    }

    /**
     * 查询结果批量修改
     *
     * @param batchUpdateDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    @Override
    public void batchUpdateToUserSelected(AppUserBatchUpdateDto batchUpdateDto) {

        if (batchUpdateDto.getMerId() == null) {
            return;
        }

        if (batchUpdateDto.getWechatUserUpdateDto() == null) {
            return;
        }

        AppUserQuery appUserQuery = batchUpdateDto.getWechatUserQuery();
        appUserQuery.setMerId(batchUpdateDto.getMerId());
        //查询总数
        Integer count = appUserMapper.findCount(appUserQuery);
        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<AppUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<AppUser> appUserList = appUserMapper.findByList(page, appUserQuery);
                if(appUserList != null && appUserList.size() > 0){
                    for(AppUser appUser : appUserList) {
                        try {
                            AppUserUpdateDto appUserUpdateDto = new AppUserUpdateDto();
                            //赋值
                            BeanUtils.copyProperties(batchUpdateDto.getWechatUserUpdateDto(), appUserUpdateDto);
                            appUserUpdateDto.setMerId(batchUpdateDto.getMerId());
                            appUserUpdateDto.setId(appUser.getId());
                            appUserUpdateDto.setLoginToken(batchUpdateDto.getLoginToken());
                            appUserService.updateToOneUser(appUserUpdateDto);

                            //营销奖励黑名单
                            //marketingRewardsBlackListService.addOrRemoveByFlag(appUser.getMerId(), String.valueOf(appUser.getId()), appUserUpdateDto.getMarketingRewardsBlackListRemark(), appUserUpdateDto.getMarketingRewardsBlackListFlag());

                        } catch (Exception e) {
                            logger.error("-------updateToOneUser is error userId={}, error={}", appUser.getId(), e.getMessage());
                        }
                    }
                }
            }
        }

//        //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//        AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
//        //有总数，且最小创建时间有
//        if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//            //则循环查询10天内的创建的会员
//            int duration = 5 * 24 * 3600;
//            List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//            if (timeVOList != null && timeVOList.size() > 0) {
//                for (TimeVO timeVO : timeVOList) {
//                    appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                    appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//
//                    //每个时间段分页查询，每页200个
//                    Page<AppUser> page = new Page<>();
//                    int current = 1;
//                    page.setCurrent(current);
//                    page.setSize(10);//最大支持10，如果此时间段数据大于10，则分页查询
//
//                    List<AppUser> wechatUserList = appUserMapper.findByList(page, appUserQuery);
//                    while (wechatUserList != null && wechatUserList.size() > 0) {
//                        for (AppUser wechatUser : wechatUserList) {
//                            try {
//                                AppUserUpdateDto appUserUpdateDto = new AppUserUpdateDto();
//                                //赋值
//                                BeanUtils.copyProperties(batchUpdateDto.getWechatUserUpdateDto(), appUserUpdateDto);
//                                appUserUpdateDto.setMerId(batchUpdateDto.getMerId());
//                                appUserUpdateDto.setId(wechatUser.getId());
//                                appUserService.updateToOneUser(appUserUpdateDto);
//                            } catch (Exception e) {
//                                logger.error("-------updateToOneUser is error userId={}, error={}", wechatUser.getId(), e.getMessage());
//                            }
//                        }
//
//                        //再次查询下一页
//                        current++;
//                        page.setCurrent(current);
//                        wechatUserList = appUserMapper.findByList(page, appUserQuery);
//                    }
//                }
//            }
//        }
    }


    /**
     * 批量修改（多选框选择会员）
     *
     * @param updateBatchDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    @Override
    public void batchUpdateToUserBatch(AppUserUpdateBatchDto updateBatchDto) {
        if (updateBatchDto.getMerId() == null) {
            return;
        }

        if (updateBatchDto.getWechatUserUpdateDto() == null) {
            return;
        }

        List<Long> idList = updateBatchDto.getIdList();
        if (idList == null || idList.size() == 0) {
            return;
        }

        if (idList != null && idList.size() > 0) {
            //查询所有机器人
            for (Long id : idList) {
                try {
                    AppUserUpdateDto appUserUpdateDto = new AppUserUpdateDto();
                    //赋值
                    BeanUtils.copyProperties(updateBatchDto.getWechatUserUpdateDto(), appUserUpdateDto);
                    appUserUpdateDto.setMerId(updateBatchDto.getMerId());
                    appUserUpdateDto.setId(id);
                    appUserUpdateDto.setLoginToken(updateBatchDto.getLoginToken());
                    appUserService.updateToOneUser(appUserUpdateDto);
                } catch (Exception e) {
                    logger.error("-------updateToOneUser is error userId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 删除所有查询的会员数据
     *
     * @param batchDeleteDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteUserSelected(AppUserBatchDeleteDto batchDeleteDto) {

        Long merId = batchDeleteDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //如果输入的验证码不是系统通用密码，则需要验证
        if(!uzaiConsoleSysConfig.getDefaultPassword().equals(batchDeleteDto.getCode())){
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }
            //验证码是否正确
            if (!codeByRedis.equals(batchDeleteDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(batchDeleteDto.getCode())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }
            //验证成功，删除验证码
            redisTemplate.delete(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
        }

        AppUserQuery appUserQuery = batchDeleteDto.getAppUserQuery();
        appUserQuery.setMerId(batchDeleteDto.getMerId());

        //查询总数
        Integer count = appUserMapper.findCount(appUserQuery);
        //每页个数
        int size = 10;
        if(Tools.getInteger(count) > 0 ){
            int totalPage = count / size + 1; //总页数
            for(int i = totalPage ; i>0;  i--){
                //每个时间段分页查询，每页200个
                Page<AppUser> page = new Page<>();
                page.setCurrent(i);
                page.setSize(size);
                List<AppUser> wechatUserList = appUserMapper.findByList(page, appUserQuery);
                if(wechatUserList != null && wechatUserList.size() > 0){
                    for(AppUser appUser : wechatUserList) {
                        try {
                            appUserService.deleteUserById(appUser.getId(), batchDeleteDto.getMerId());
                        } catch (Exception e) {
                            logger.error("-------deleteUserById is error userId={}, error={}", appUser.getId(), e.getMessage());
                        }
                    }
                }
            }
        }

//        //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//        AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
//        //查询总数
//        Integer count = appUserMapper.findCount(appUserQuery);
//        //有总数，且最小创建时间有
//        if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//            //则循环查询5天内的创建的会员
//            int duration = 5 * 24 * 3600;
//            List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//            if (timeVOList != null && timeVOList.size() > 0) {
//                for (TimeVO timeVO : timeVOList) {
//                    appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                    appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//
//                    //每个时间段分页查询，每页200个
//                    Page<AppUser> page = new Page<>();
//                    int current = 1;
//                    page.setCurrent(current);
//                    page.setSize(10);//最大支持10，如果此时间段数据大于10，则分页查询
//
//                    List<AppUser> wechatUserList = appUserMapper.findByList(page, appUserQuery);
//                    while (wechatUserList != null && wechatUserList.size() > 0) {
//                        for (AppUser wechatUser : wechatUserList) {
//                            try {
//                                appUserService.deleteUserById(wechatUser.getId(), batchDeleteDto.getMerId());
//                            } catch (Exception e) {
//                                logger.error("-------deleteUserById is error userId={}, error={}", wechatUser.getId(), e.getMessage());
//                            }
//                        }
//                        wechatUserList = appUserMapper.findByList(page, appUserQuery);
//                    }
//                }
//            }
//        }
    }

    /**
     * 批量删除会员数据（多选框）
     *
     * @param appUserIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteUserBatch(AppUserIdListDto appUserIdListDto) {
        Long merId = appUserIdListDto.getMerId();
        Merchant merchant = merchantService.findByMerId(merId);
        if(merchant == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商不存在");
        }

        //如果输入的验证码不是系统通用密码，则需要验证
        if(!uzaiConsoleSysConfig.getDefaultPassword().equals(appUserIdListDto.getCode())){
            //获取存在redis中的验证码
            String codeByRedis = (String) redisTemplate.opsForValue().get(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
            //判断验证码是否过期
            if (StringUtils.isBlank(codeByRedis)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_MISS);
            }
            //验证码是否正确
            if (!codeByRedis.equals(appUserIdListDto.getCode()) && !uzaiConsoleSysConfig.getDefaultPassword().equals(appUserIdListDto.getCode())){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.CODE_ERR);
            }
            //验证成功，删除验证码
            redisTemplate.delete(String.format(SmsType.USER_DATA_DELETE.getDesc(), merchant.getMobile()));
        }

        //封装批量删除的用户ID
        List<Long> idList = appUserIdListDto.getIdList();
        if (appUserIdListDto.getIdList() != null && appUserIdListDto.getIdList().size() > 0) {
            for (Long id : idList) {
                try {
                    appUserService.deleteUserById(id, appUserIdListDto.getMerId());
                } catch (Exception e) {
                    logger.error("-------deleteUserById is error userId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 批量删除下级会员数据（多选框）
     *
     * @param deleteSonBatchDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteSonWechatUserBatch(AppUserDeleteSonBatchDto deleteSonBatchDto) {

        if (deleteSonBatchDto.getIdentity() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "身份参数不能为空");
        }

        //封装批量删除的用户ID
        List<Long> idList = deleteSonBatchDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择需要删除的下级成员");
        }

        for (Long id : idList) {
            try {
                AppUserDeleteSonDto appUserDeleteSonDto = new AppUserDeleteSonDto();
                BeanUtils.copyProperties(deleteSonBatchDto, appUserDeleteSonDto);
                appUserDeleteSonDto.setId(id);
                appUserDeleteSonDto.setIdentity(deleteSonBatchDto.getIdentity());
                appUserDeleteSonDto.setMerId(deleteSonBatchDto.getMerId());
                appUserService.deleteSonWechatUser(appUserDeleteSonDto);
            } catch (Exception e) {
                logger.error("-------appUserService.deleteSonWechatUser is error userId={}, error={}", id, e.getMessage());
            }
        }
    }

    /**
     * 异步修改个人微信默认客户端
     *
     * @param defaultClientDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    public void updateDefaultClientSync(AppBatchUpdateDefaultClientDto defaultClientDto) {
        Long merId = defaultClientDto.getMerId();
        if (merId == null) {
            return;
        }

        Long deviceUniqueIdOld = defaultClientDto.getDeviceUniqueIdOld();
        if (deviceUniqueIdOld == null) {
            return;
        }

        Long deviceUniqueIdNew = defaultClientDto.getDeviceUniqueIdNew();
        if (deviceUniqueIdNew == null) {
            return;
        }

        List<Long> userTypeIdOldList = defaultClientDto.getUserTypeIdOldList();

        if (userTypeIdOldList == null || userTypeIdOldList.size() == 0) {
            return;
        }

        List<Long> userTypeIdNewList = defaultClientDto.getUserTypeIdNewList();
        if (userTypeIdNewList == null || userTypeIdNewList.size() == 0) {
            return;
        }

        //是否转移订单默认客户端
        Integer transferDataFlag = defaultClientDto.getTransferDataFlag();
        if (Tools.getInteger(transferDataFlag).intValue() == 1) { //转移订单的默认客户端
            //转移淘宝订单
            tbOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移京东订单
            jdOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移拼多多订单
            pddOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移唯品会订单
            vphOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移美团订单
            mtOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
            //转移抖音订单
            dyOrderMapper.batchUpdateDeviceInfo(deviceUniqueIdOld, deviceUniqueIdNew, merId);
        }


        //新的会员类型列表长度必须大于旧的会员类型列表长度
        if (userTypeIdNewList.size() < userTypeIdOldList.size()) {
            return;
        }

        for (int i = 0; i < userTypeIdOldList.size(); i++) {

            Long userTypeIdOld = userTypeIdOldList.get(i);
            UserType userTypeOld = userTypeMapper.selectById(userTypeIdOld, merId);
            if (userTypeOld == null) {
                continue;
            }

            Long userTypeIdNew = userTypeIdNewList.get(i);
            UserType userTypeNew = userTypeMapper.selectById(userTypeIdNew, merId);
            if (userTypeNew == null) {
                continue;
            }

            //身份不一样，则跳过不修改
            if (Tools.getInteger(userTypeOld.getIdentity()).intValue() != Tools.getInteger(userTypeNew.getIdentity()).intValue()) {
                continue;
            }

            //修改会员默认客户端
            UpdateDefaultClient updateDefaultClient = new UpdateDefaultClient();
            updateDefaultClient.setMerId(merId);
            updateDefaultClient.setDeviceUniqueIdOld(deviceUniqueIdOld);
            updateDefaultClient.setDeviceUniqueIdNew(deviceUniqueIdNew);
            updateDefaultClient.setUserTypeIdOld(userTypeIdOld);
            updateDefaultClient.setUserTypeIdNew(userTypeIdNew);
            appUserMapper.updateDefaultClient(updateDefaultClient);
        }
    }

}
